// 包装 useFetch 函数，使其返回一个 Promise 对象
interface myFetchOptions {
  headers?: Record<string, string>;
  [key: string]: any;
}

export const useHttpFetch = (url: string, opt: myFetchOptions) => {
  // token
  const token = useCookie("token");
  // 结构opt
  const headers = {
    ...opt.headers,
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
  opt.headers = headers;

  return useFetch(url, {
    ...opt,
    baseURL: "", // 基本url
    // https://nuxt.com/docs/api/composables/use-fetch 拦截器
    onRequest({ request, options }) {
      // Set the request headers
      //   options.headers = options.headers || {};
      //   options.headers.authorization = "...";
      console.log("request", request);
    },
    onRequestError({ request, options, error }) {
      // Handle the request errors
      console.error("request", request);
    },
    onResponse({ request, response, options }) {
      // Process the response data
      //   localStorage.setItem("token", response._data.token);
      console.log("response", response);
    },
    onResponseError({ request, response, options }) {
      // Handle the response errors
      console.error("response", response);
    },
  });
};


// 上面定义了 通用的接口
// 使用，这里定义具体的接口调用
export const useInfoFetch = (opt: myFetchOptions) => {
    return useHttpFetch("/api/info", opt);
}
